#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
#include <sys/stat.h>
#include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() */

#include "Header.h"

#define BUFSIZE 1024   /* Size of receive buffer */

void DieWithError(char *errorMessage);  /* Error handling function */

int main(int argc, char *argv[]) {
    int sock;                        /* Socket descriptor */
    struct sockaddr_in echoServAddr; /* Echo server address */
    unsigned short echoServPort;     /* Echo server port */
    char *servIP;                    /* Server IP address (dotted quad) */
    FILE *fp;
    struct stat fst;

    if ((argc < 3) || (argc > 4)){    /* Test for correct number of arguments */
      fprintf(stderr, "Usage: %s <Server IP> <Filename> [<Echo Port>]\n", argv[0]);
      exit(1);
    }
	servIP = argv[1];             /* First arg: server IP address (dotted quad) */
	//echoString = argv[2];         /* Second arg: string to echo */

	if (argc == 4)
	    echoServPort = atoi(argv[3]); /* Use given port, if any */
	else
    	echoServPort = 7;  /* 7 is the well-known port for the echo service */

	/* Create a reliable, stream socket using TCP */
	if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    	DieWithError("socket() failed");

	/* Construct the server address structure */
	memset(&echoServAddr, 0, sizeof(echoServAddr));     /* Zero out structure */
	echoServAddr.sin_family      = AF_INET;             /* Internet address family */
	echoServAddr.sin_addr.s_addr = inet_addr(servIP);   /* Server IP address */
	echoServAddr.sin_port        = htons(echoServPort); /* Server port */

	if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
        DieWithError("connect() failed");

	printf("File Sending Start\n");
	stat(argv[2], &fst);
	printf("file size : %d\n", fst.st_size);
    if((fp = fopen(argv[2], "r")) != 0) {
		file_header h;
		char buf[BUFSIZE];
		int oldSize = 0;

		memset(&h, 0, sizeof(h));
		h.len = fst.st_size;
		strcpy(h.filename, argv[2]);
		h.uid = fst.st_uid;
		h.gid = fst.st_gid;
		h.perm = fst.st_mode;

		send(sock, &h, sizeof(h), 0);

		recv(sock, &oldSize, sizeof(oldSize), 0);

		if(oldSize < h.len) {
			fseek(fp, SEEK_SET, oldSize);
			while(!feof(fp)) {
				int len;

				memset(buf, 0, sizeof(buf));
				len = fread(buf, sizeof(char), BUFSIZE, fp);
				send(sock, buf, len, 0);
			}
		}
		
		fclose(fp);

    }
    printf("File Sending End\n");    /* Print a final linefeed */
    close(sock);
    return 0;
}

/*--- Inform (X)Emacs about preferred coding style ---------------------*/
/*
 * Local Variables:
 * mode: c
 * c-file-style: "linux"
 * indent-tabs-mode: t
 * tab-width: 4
 * fill-column: 78
 * ispell-local-dictionary: "korean"
 * End:
 */
